<template>
  <div class="params">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->
    <el-card>
      <!-- 警告 -->
      <el-alert title="注意:只允许为第三级分类标签设置相关阐述" type="warning" show-icon></el-alert>

      <!-- 联级选择器 -->
      <span>选择商品分类：</span>
      <el-cascader v-model="selectedCate" :options="cateList" :props="cateListProps"
        @change="cascaderChange"></el-cascader>

      <!-- nav -->
      <el-tabs v-model="activeName" @tab-click="getAttribute">
        <!-- 动态参数 -->
        <el-tab-pane label="动态参数" name="only">
          <el-button type="primary" :disabled="isBth" @click="addAttributeDiaglose">添加参数</el-button>

          <!-- 属性展示 -->
          <el-table :data="attributeList" style="width: 100%">
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag v-for="(item, i) in scope.row.attr_vals" :key="i" closable
                  @close="deleteAttributeTag(scope.row, i)">{{ item }}></el-tag>

                <!-- 添加标签 -->
                <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue"
                  ref="saveTagInput" @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)">
                </el-input>
                <el-button v-else size="small" @click="showInput(scope.row)">+ New Tag</el-button>

              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="attr_name" label="属性名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" icon="el-icon-edit" @click="editAttribute(scope.row)">修改</el-button>
                <el-button type="danger" icon="el-icon-delete" @click="deleteAttribute(scope.row.attr_id)">
                  删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <!-- 静态属性 -->
        <el-tab-pane label="静态属性" name="many">
          <el-button type="primary" :disabled="isBth" @click="addAttributeDiaglose">添加属性</el-button>

          <!-- 属性展示 -->
          <el-table :data="attributeList" style="width: 100%">
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag v-for="(item, i) in scope.row.attr_vals" :key="i" closable
                  @close="deleteAttributeTag(scope.row, i)">{{ item }}></el-tag>

                <!-- 添加标签 -->
                <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue"
                  ref="saveTagInput" @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)">
                </el-input>
                <el-button v-else size="small" @click="showInput(scope.row)">+ New Tag</el-button>

              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="attr_name" label="属性名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" icon="el-icon-edit" @click="editAttribute(scope.row)">修改</el-button>
                <el-button type="danger" icon="el-icon-delete">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加属性对话框 -->
    <el-dialog title="提示" :visible.sync="isAddAttributeDiaglose" width="50%">
      <el-form ref="addAttributeRef" :model="addAttributeForm" :rules="addAttributeRules" label-width="auto">
        <el-form-item :label="'添加' + (activeName == 'only' ? '参数' : '属性') + '：'" prop="attr_name">
          <el-input v-model="addAttributeForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isAddAttributeDiaglose = false">取 消</el-button>
        <el-button type="primary" @click="addAttribute">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑属性对话框 -->
    <el-dialog title="编辑属性" :visible.sync="isEditAttributeDialogVisible" width="50%">
      <el-form ref="editAttributeRef" :model="editAttributeForm" :rules="editAttributeRules" label-width="auto">
        <el-form-item :label="(activeName == 'only' ? '参数' : '属性') + '名称：'" prop="attr_name">
          <el-input v-model="editAttributeForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isEditAttributeDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateAttribute">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>

export default {
  data () {
    return {
      cateList: [], // 所有的商品分类
      cateListProps: { // 联级选择器配置项
        expandTrigger: 'hover',
        value: 'cat_id',
        children: 'children',
        label: 'cat_name'
      },
      selectedCate: [], // 被选中的商品分类
      activeName: 'only', // 当前选中的nav
      isBth: true, // 添加参数按钮是否能继续使用,true为否
      attributeList: [], // 获取到的属性/参数列表
      isAddAttributeDiaglose: false, // 添加参数弹窗
      addAttributeForm: { // 添加属性/参数的内容
        attr_name: ''
      },
      addAttributeRules: {
        attr_name: { required: true, message: '请输入活动名称', trigger: 'blur' }
      },
      isEditAttributeDialogVisible: false, // 编辑属性对话框显示状态
      editAttributeForm: { // 编辑属性表单
        attr_id: 0,
        attr_name: ''
      },
      editAttributeRules: { // 编辑属性验证规则
        attr_name: { required: true, message: '请输入属性名称', trigger: 'blur' }
      }

    }
  },

  methods: {
    // 获取商品分类列表
    async getCate () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return this.$message.error('获取列表失败')
      this.cateList = res.data
    },

    // 联级选择器的值发生改变时触发
    cascaderChange () {
      if (this.selectedCate.length !== 3) {
        this.isBth = true
        this.attributeList = []
      } else {
        this.isBth = false
        this.getAttribute()
      }
    },

    // 获取属性/参数
    async getAttribute () {
      if (this.selectedCate.length !== 3) return
      const { data: res } = await this.$http.get(`categories/${this.selectedCate[2]}/attributes`, { params: { sel: this.activeName } })
      if (res.meta.status !== 200) return this.$message.error('获取数据失败')
      res.data.forEach(Item => {
        Item.attr_vals = Item.attr_vals ? Item.attr_vals.split(',') : []
        Item.inputValue = ''
        Item.inputVisible = false
      })
      this.attributeList = res.data
    },

    // 展示添加属性对话框
    addAttributeDiaglose () {
      this.isAddAttributeDiaglose = true
    },

    // 添加属性/参数
    addAttribute () {
      this.$refs.addAttributeRef.validate(async valid => {
        if (!valid) return this.$message.error('请填写信息')
        const { data: res } = await this.$http.post(`categories/${this.selectedCate[2]}/attributes`, {
          attr_name: this.addAttributeForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 201) return this.$message.error('添加失败')
        this.$message.success('添加成功')
        this.isAddAttributeDiaglose = false
        this.getAttribute()
      })
    },

    // 编辑属性对话框
    editAttribute (attribute) {
      this.editAttributeForm.attr_id = attribute.attr_id
      this.editAttributeForm.attr_name = attribute.attr_name
      this.isEditAttributeDialogVisible = true
    },

    // 更新属性
    updateAttribute () {
      this.$refs.editAttributeRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put(
          `categories/${this.selectedCate[2]}/attributes/${this.editAttributeForm.attr_id}`,
          {
            attr_name: this.editAttributeForm.attr_name,
            attr_sel: this.activeName
          }
        )

        if (res.meta.status !== 200) return this.$message.error('更新失败')
        this.$message.success('更新成功')
        this.isEditAttributeDialogVisible = false
        this.getAttribute()
      })
    },
    deleteAttribute (attrId) {
      this.$confirm('此操作将永久删除该属性, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.delete(
          `categories/${this.selectedCate[2]}/attributes/${attrId}`,
          { params: { attr_sel: this.activeName } }
        )

        if (res.meta.status !== 200) return this.$message.error('删除失败')

        this.$message({
          type: 'success',
          message: '删除成功!'
        })

        // 重新获取属性列表
        this.getAttribute()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },

    // 处理添加属性/参数的输入框回车事件
    async handleInputConfirm (row) {
      row.inputValue = row.inputValue.trim()
      if (row.inputValue === '') return
      row.attr_vals.push(row.inputValue)
      const { data: res } = await this.$http.put(`categories/${this.selectedCate[2]}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(',')
        })
      if (res.meta.status !== 200) return this.$message.error('添加失败')
      this.$message.success('添加成功')
      row.inputValue = ''
      row.inputVisible = false
      this.getAttribute()
    },

    // 展示添加按钮输入框
    showInput (row) {
      row.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },

    // 删除参数标签
    async deleteAttributeTag (row, index) {
      // 从数组中移除指定索引的标签
      row.attr_vals.splice(index, 1)

      // 发送请求更新服务器数据
      const { data: res } = await this.$http.put(
        `categories/${this.selectedCate[2]}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(',')
        }
      )

      if (res.meta.status !== 200) {
        this.$message.error('删除标签失败')
        // 如果删除失败，可以考虑恢复原来的状态
        return
      }

      this.$message.success('删除标签成功')
      // 不需要重新获取属性列表，因为我们已经直接修改了本地数据
    }
  },

  created () {
    this.getCate()
  }
}
</script>

<style>
.el-tag {
  margin: 5px;
}

.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
